package com.linkage.jz.bankruptcy.fragment.Project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProTalkActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ProTalkDetailActivity;
import com.linkage.jz.bankruptcy.base.BaseActivity;
import com.linkage.jz.bankruptcy.bean.ProTalk;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.widget.datepicker.DateFormatUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author AFAP
 * Fragment-讨论
 */
public class ProTalkFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    public static final String MERCHANT_DETAILS_PAGE = "MERCHANT_DETAILS_PAGE";

    private RecyclerView mRecyclerView;
    private TalkAdapter mAdapter;
    private String mProjectId;
    private List<ProTalk> mData;

    private boolean addDiscussion = false;

    int page = 1;
    private SwipeRefreshLayout swipe;

    public static ProTalkFragment newInstance(int page, String infoid) {
        Bundle args = new Bundle();
        args.putInt(MERCHANT_DETAILS_PAGE, page);
        args.putString("infoid", infoid);
        ProTalkFragment tripFragment = new ProTalkFragment();
        tripFragment.setArguments(args);
        return tripFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mProjectId = getArguments().getString("infoid");
        mData = new ArrayList<>();
    }

    @Override
    public void onResume() {
        super.onResume();
        ProDetailActivity parentActivity = (ProDetailActivity) getActivity();
        parentActivity.showLoading();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_pro_detailpro_talk, container, false);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        swipe = view.findViewById(R.id.swipe);
        view.findViewById(R.id.tv_pro_module_item_add).setOnClickListener(this);
        view.findViewById(R.id.ll_pro_module_item_add).setOnClickListener(this);

        initAdapter(mData);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        swipe.setColorSchemeColors(0xff25b6ed, 0xff6dbcdb, 0xfff0b650, 0xffff534e, 0xffbed73d, 0xff04bfbf,
                0xffff530d, 0xff61bc46);
        swipe.setOnRefreshListener(this);
        onRefresh();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_pro_module_item_add:
            case R.id.tv_pro_module_item_add:
                Intent intent = new Intent(getActivity(), CreateProTalkActivity.class);
                intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                startActivity(intent);
        }
    }


    private void refreshAction() {
        View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
        View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
        TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
        TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
        TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
        tv_pro_module_nodata_tip.setText("还没有任何讨论话题");
        tv_pro_module_item_add.setText("发起话题");
        tv_pro_module_item_add0.setText("发起话题");

        if (addDiscussion) {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.VISIBLE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.VISIBLE);
            }
        } else {
            if (mData.size() > 0) {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.GONE);
            } else {
                ll_pro_module_item_add.setVisibility(View.GONE);
                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                tv_pro_module_item_add.setVisibility(View.GONE);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_TALK)) {
            onRefresh();
        }
    }

    /**
     * 设置RecyclerView属性
     */
    private void initAdapter(final List<ProTalk> data) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new TalkAdapter(getActivity(), R.layout.fragment_pro_detailpro_talk_item, data);
        mAdapter.openLoadAnimation();
        mRecyclerView.setAdapter(mAdapter);//设置adapter
        //设置item点击事件
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.ll_talkitem:
                        Intent intent = new Intent(getActivity(), ProTalkDetailActivity.class);
                        intent.putExtra(BaseActivity.KEY_PROJECTID, mProjectId);
                        intent.putExtra(ProTalkDetailActivity.KEY_ID, data.get(position).getId());
                        startActivity(intent);
                        break;

                }
            }
        });
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        page = 1;
        getList();
    }

    class TalkAdapter extends BaseQuickAdapter<ProTalk, BaseViewHolder> {
        int mLayoutId;

        public TalkAdapter(Context context, int LayoutId, List<ProTalk> str) {
            super(LayoutId, str);
            Log.e("=========----====talk", LayoutId + "");
            mLayoutId = LayoutId;
        }

        @Override
        public void convert(BaseViewHolder helper, ProTalk info) {
            helper.setText(R.id.tv_talkname, info.getUsername());
            helper.addOnClickListener(R.id.ll_talkitem);

            String title = "";
            if ("1".equalsIgnoreCase(info.getSubjectType())) {
                title = "【债权人话题】";
            } else if ("0".equalsIgnoreCase(info.getSubjectType())) {
                title = "【债委会话题】";
            }
            TextView tv_talktitle = helper.getView(R.id.tv_talktitle);
            if (info.isHasPictures()) {
                title = title + " " + info.getSubjectTitle(); // 加个空格留着替换为图片
                ImageSpan imgSpan = new ImageSpan(getActivity(), R.drawable.ic_pro_talk_atta_list,
                        DynamicDrawableSpan.ALIGN_BASELINE);
                SpannableString spannableString = new SpannableString(title);
                spannableString.setSpan(imgSpan, 7, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                tv_talktitle.setText(spannableString);
            } else {
                title = title + info.getSubjectTitle();
                tv_talktitle.setText(title);
            }


            ImageView imageview = helper.getView(R.id.avatarImageView);
            Glide.with(getActivity()).load(info.getAvatar())
                    .bitmapTransform(new CropCircleTransformation(getActivity()))
                    .placeholder(R.drawable.logo)
                    .into(imageview);

            String strTime = DateFormatUtils.long2Str(info.getCreateTime(), true);
            helper.setText(R.id.tv_talktime, strTime);
            helper.setText(R.id.tv_talkreply, "回复 " + info.getCnt());
        }
    }

    public void getList() {
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken", "");

//        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null ||"".equalsIgnoreCase(userToken)) {
////            emptyView.setVisibility(View.VISIBLE);
//            View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
//            View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
//            TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
//            TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
//            TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
//            tv_pro_module_nodata_tip.setText("还没有任何讨论话题");
//            tv_pro_module_item_add.setText("发起话题");
//            tv_pro_module_item_add0.setText("发起话题");
//            area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
//            tv_pro_module_item_add.setVisibility(View.GONE);
//            return;
//        }
        Network
                .getAPIService()
                .getTalkList(userToken, mProjectId, page, 10)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
//                            super.onNext(json);
                            if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null ||"".equalsIgnoreCase(userToken)) {
//            emptyView.setVisibility(View.VISIBLE);
                                View ll_pro_module_item_add = getView().findViewById(R.id.ll_pro_module_item_add);
                                View area_pro_module_nodata_tip = getView().findViewById(R.id.area_pro_module_nodata_tip);
                                TextView tv_pro_module_item_add0 = getView().findViewById(R.id.tv_pro_module_item_add0);
                                TextView tv_pro_module_item_add = getView().findViewById(R.id.tv_pro_module_item_add);
                                TextView tv_pro_module_nodata_tip = getView().findViewById(R.id.tv_pro_module_nodata_tip);
                                tv_pro_module_nodata_tip.setText("还没有任何讨论话题");
                                tv_pro_module_item_add.setText("发起话题");
                                tv_pro_module_item_add0.setText("发起话题");
                                area_pro_module_nodata_tip.setVisibility(View.VISIBLE);
                                tv_pro_module_item_add.setVisibility(View.GONE);
                                return;
                            }
                            return;
                        }
                        JsonObject data = json.getAsJsonObject("data");
                        int total = data.getAsJsonObject("subjectList").get("totalCount").getAsInt();
                        addDiscussion = data.getAsJsonObject("auth").get("addDiscussion").getAsBoolean();
                        JsonArray arr = data.getAsJsonObject("subjectList").getAsJsonArray("list");
                        List<ProTalk> list = ProTalk.parse(arr);
                        if (page == 1)
                            mData.clear();
                        page++;
                        mData.addAll(list);
                        if (mData.size() < total) {
                            mAdapter.loadMoreComplete();
                        } else {
                            mAdapter.loadMoreEnd();
                        }
                        refreshAction();
                    }

                    @Override
                    public void onCompleted() {
                        swipe.setRefreshing(false);
                        mAdapter.setEnableLoadMore(true);
                    }

                    @Override
                    public void onError(Throwable e) {
                        mAdapter.loadMoreFail();
                    }
                });
    }
}
